<?php
namespace app\web\admin;

use app\common\builder\ZBuilder;
use app\web\model\Platform;
use app\web\model\User as MyModel;
use app\web\model\UserBalance;
use app\web\model\UserIntegral;
use app\web\model\Shop;
use app\web\model\Technician;
use app\web\model\Config;
use app\lib\model\Price;
use Yansongda\Pay\Pay;

/**
 * 章节管理
 * @package
 */
class User extends Base 
{
    private $gender = ['未授权','男','女'];
    private $appkey = ['用户端','技师端','商户端'];
	private $status = ['未审核','已通过','未通过'];
	public function index()
	{
		$map = $this->getMap();
		
		$data_list = MyModel::where($map)->where('nickName','<>','')
					->order($this->getOrder("id desc"))
					->paginate();
		return ZBuilder::make('table')
			->hideCheckbox()
			->setTableName('user')
			->setSearch(['mobile' => '手机号','nickName'=>'昵称']) // 设置搜索参数
			->addColumns([
				['avatarUrl','头像','img_url'],
				['nickName','昵称'],
				['gender','性别','status','',$this->gender],
                ['mobile','手机号'],
				['wx_code','微信号'],
                ['integral','积分'],
				['balance','余额'],
                ['status','是否拉黑','status','',['否','是']],
                ['withdrawal_balance','可提现余额'],
				['create_time','创建时间'],
                ['right_button', '操作', 'btn']
			])
			->addOrder('balance,integral,withdrawal_balance')
            ->addRightButton('edit',['title'=>'拉黑'])
			->setRowList($data_list)
			->fetch();
	}
    public function edit($id=null)
    {
        $user = MyModel::get($id);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['status'] == 1 && empty($data['block_desc'])) $this->error('请输入拉黑备注');
            if ($user->save($data)) {
                $this->success('编辑成功','index');
            } else {
                $this->error('编辑失败');
            }
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['static', 'nickName', '用户昵称'],
                ['radio', 'status', '是否拉黑', '', ['否', '是']],
                ['text','block_desc','拉黑备注'],
            ])
            ->setTrigger('status','1','block_desc')
            ->setFormData($user)
            ->fetch();
    }
    /**
     * 积分明细
     * [integral description]
     * @return [type] [description]
     */
    public function integral()
    {
        $map = $this->getMap();
        $list = UserIntegral::alias('a')
                            ->where($map)
                            ->leftjoin('user b','b.id=a.user_id')
                            ->field('a.id,a.integral_type,a.change_integral,a.status,a.create_time,b.nickName,b.mobile')
                            ->order($this->getOrder('a.create_time desc'))
                            ->paginate();
        return ZBuilder::make('table')
                ->hideCheckbox()
                ->setTableName('user_integral')
                ->setSearch(['mobile'=>'用户电话','nickName'=>'用户昵称'])
                ->addColumns([
                    ['nickName','用户昵称'],
                    ['mobile','用户电话'],
                    ['integral_type','积分变动类型','status','',['消费获得积分','积分抵扣','退款返回积分']],
                    ['change_integral','变动积分'],
                    ['status','是否到账','status','',['否','是']],
                    ['create_time','变动时间'],
                ])
                ->addOrder('create_time,change_integral')
                ->addFilterList('integral_type',['消费获得积分','积分抵扣','退款返回积分'])
                ->setRowList($list)
                ->fetch();
    }
    public function balance()
    {
        $map = $this->getMap();
        $map[] = ['a.status','=',1];
        foreach ($map as $key => $value) {
            if($value[0] == 'create_time') $map[$key][0] = 'a.create_time';
        }
        $list = UserBalance::alias('a')
                            ->leftjoin('user b','b.id=a.user_id')
                            ->where($map)
                            ->field('a.id,a.change_balance,a.before_balance,a.after_balance,a.status,a.balance_type,a.create_time,b.nickName,b.mobile,a.notes,b.wx_code,b.city')
                            ->order($this->getOrder('a.create_time desc'))
                            ->paginate();
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('user_balance')
            ->setSearch(['nickName' => '昵称','mobile'=>'用户电话','city'=>'城市']) // 设置搜索参数
            ->addColumns([
                ['nickName','昵称'],
                ['wx_code','微信号'],
                ['mobile','用户电话'],
                ['city','所在城市'],
                ['balance_type','变动类型','status','',['充值','消费','退款','佣金','提现']],
                ['before_balance','变动前金额'],
                ['change_balance','变动金额'],
                ['after_balance','变动后金额'],
                ['notes','备注'],
                ['create_time','变动时间'],
            ])
            ->addTimeFilter('create_time','','变动时间')
            ->addOrder('change_balance,create_time')
            ->addFilterList('balance_type',['充值','消费','退款','佣金','提现'])
            ->setRowList($list)
            ->fetch();
    }
    public function withdrawal()
    {
        $map = $this->getMap();
        $map[] = ['a.balance_type','=',4];
        $list = UserBalance::alias('a')
                        ->leftjoin('user b','b.id=a.user_id')
                        ->field('a.id,abs(a.change_balance) as change_balance,a.status,b.nickName,b.mobile,a.create_time')
                        ->where($map)
                        ->order($this->getOrder('a.id desc'))
                        ->paginate();
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('user_balance')
            ->setSearch(['nickName' => '昵称','mobile'=>'用户电话']) // 设置搜索参数
            ->addColumns([
                ['nickName','昵称'],
                ['mobile','用户电话'],
                ['change_balance','提现金额'],
                ['status','审核状态','status','',['未审核','已通过','未通过']],
                ['create_time','提交时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addOrder('change_balance,create_time')
            ->addFilterList('status',$this->status)
            ->addRightButtons(['check'=>['title'=>'审核','href'=>url('check',['id'=>'__id__'])]])
            ->replaceRightButton(['status' => ['in','1,2']], '','check') // 修改id为1的按钮
            ->setRowList($list)
            ->fetch();
    }
    /**
     * 提现审核
     * [check description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
	public function check($id)
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            $info = UserBalance::get($data['id']);
            if($data['status'] == 0) $this->success('操作成功' ,'withdrawal');
            if($data['status'] == 2){
                $res = $info->save($data);
                if(!$res) $this->error('操作失败');
                $this->success('操作成功','withdrawal');
            }
            if($data['status'] == 1){
                $user = MyModel::get($info['user_id'])->getData();
                $order = [
                    'partner_trade_no' => $this->getOrderNo(),              //商户订单号
                    'openid' => $user['openid'],                        //收款人的openid
                    'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
                    // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
                    'amount' => Price::priceyuantofen(-$info['change_balance']),                       //企业付款金额，单位为分
                    'desc' => '帐户提现',                  //付款说明
                    'type' => 'miniapp'
                ];

                try{
                    $res = Pay::wechat(Config::getWechatConfig($info['appkey']))->transfer($order);
                } catch (\Exception $e) {
                    $this->error("支付接口异常".$e->getMessage());
                }  
                if($res['return_code'] == 'SUCCESS'){
                    $data['before_balance'] = $user['balance'];
                    $af_balanc = Price::pricecalc($user['balance'],'+',$info['change_balance']);
                    $data['after_balance'] = $af_balanc;
                
                    MyModel::where(['id'=>$user['id']])->update(['balance'=>$af_balanc,'withdrawal_balance'=>Price::pricecalc($user['withdrawal_balance'],'+',$info['change_balance'])]);
                    
                    $info->save($data);
                    Platform::change([
                        'role' => 0,
                        'p_id' => $user['id'],
                        'platform_type' => 4,
                        'mobile' => $user['mobile'],
                        'user_name' => $user['nickName'],
                        'change_balance' => $info['change_balance'],
                        'notes' => '用户提现到零钱'
                    ]);
                    $this->success('提现成功','withdrawal');
                }
                $this->error('提现失败');
            }
        }
        $info = UserBalance::field('id,user_id,abs(change_balance) as change_balance,status')->get($id);
        $info->tot_withdrawal = UserBalance::where(['user_id'=>$info->user_id,'balance_type'=>4,'status'=>1])->sum('change_balance');
        $info->tot_withdrawal = abs($info->tot_withdrawal);
        $info->withdrawal_balance = MyModel::where('id',$info->user_id)->value('withdrawal_balance');
        $info->wx_code = MyModel::where('id',$info->user_id)->value('wx_code');
        $list = UserBalance::where(['user_id'=>$info->user_id,'balance_type'=>4,'status'=>1])
                            ->field('id,user_id,abs(change_balance) as change_balance,create_time')
                            ->select()
                            ->toArray();
        $info['order_goods'] = $list;
        $content = "";
        foreach ($list as $key => $v) {
            $content .= "<tr>
                            <td>{$v['change_balance']}</td>
                            <td>{$v['create_time']}</td>
                        </tr>";
        }
        $html = <<<EOF
<div  id="product-table" style="display:none">
    <table class="table table-builder table-hover table-bordered table-striped ">
        <tr>
            <th>提现金额</th>
            <th>提现时间</th>
        </tr>
        {$content}
    </table>
</div>
<script>
    $(function(){
        $("#form_group_goods .form-control-static").html($("#product-table").html());

    })
</script>
EOF;
        return ZBuilder::make('form')
            ->setPageTips('审核通过后提现金额直接到账微信')
            ->addFormItems([
                ['hidden','id'],
                // ['static','wx_code','用户微信号'],
                ['static','withdrawal_balance','该用户可提现余额(元)'],
                ['static','tot_withdrawal','该用户总共提现金额(元)'],
                ['static', 'change_balance','提现金额'],
                ['radio', 'status', '状态', '', $this->status, 1],
            ])
            ->addStatic('goods', '提现记录')
            ->setExtraHtml($html)
            ->setFormData($info)
            ->fetch();
    }
}